import React, { useEffect, useState } from 'react';
import FillTable from "./FillTable";
import styles from "./SelectTable.module.css";

export default function SelectTable({
  keepSelect,
  keepCheck,
  selectedRowKey,
  className,
  style,
  rowSelection,
  rowClassName = () => '',
  onRow = () => ({}),
  ...props
}) {
  const [selected, setSelected] = useState(null);
  const [checkedRows, setCheckedRows] = useState([]);
  const {
    onSelect = () => { },
    onSelectAll = () => { },
    onSelectNone = () => { },
    onSelectMultiple = () => { },
    ...rowSelectionOther
  } = rowSelection || {};

  useEffect(() => {
    if (!keepSelect) setSelected(null);
    if (!keepCheck) setCheckedRows([]);
  }, [keepSelect, keepCheck, props.dataSource]);

  return <FillTable className={[styles.table, className].join(' ')}
    rowSelection={{
      selectedRowKeys: checkedRows.map(r => r.ID),
      ...rowSelectionOther,
      onSelect: (record, selected, selectedRows) => setCheckedRows(selectedRows) || onSelect(record, selected, selectedRows),
      onSelectAll: (selected, selectedRows) => setCheckedRows(selectedRows) || onSelectAll(selected, selectedRows),
      onSelectNone: () => setCheckedRows([]) || onSelectNone(),
      onSelectMultiple: (selected, selectedRows, changeRows) => setCheckedRows(selectedRows) || onSelectMultiple(selected, selectedRows, changeRows)
    }}
    rowClassName={record => {
      if (selectedRowKey) {
        return (selectedRowKey === record.ID ? 'selecttable-row-highlight' : '') + rowClassName(record);
      } else {
        return (selected === record ? 'selecttable-row-highlight' : '') + rowClassName(record);
      }
    }}
    onRow={(record) => {
      const { onClick = () => { }, ...other } = onRow(record);
      return {
        onClick: () => setSelected(selected === record ? null : record) || onClick(),
        ...other,
      };
    }}
    {...props} />;
}